package com.wss.module.wan.ui.main.fragment;

import cn.bingoogolapple.refreshlayout.BgaStickinessRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BgarefreshLayout;
import com.felipecsl.asymmetricgridview.AsymmetricRecyclerView;
import com.felipecsl.asymmetricgridview.AsymmetricRecyclerViewAdapter;
import com.orhanobut.logger.Logger;
import com.wss.common.base.BaseMvpFragment;
import com.wss.common.base.adapter.listener.OnListItemClickListener;
import com.wss.common.bean.Template;
import com.wss.common.manage.AbilityToAbility;
import com.wss.common.utils.ImageUtils;
import com.wss.common.utils.ToastUtils;
import com.wss.module.wan.ResourceTable;
import com.wss.module.wan.bean.Article;
import com.wss.module.wan.bean.BannerInfo;
import com.wss.module.wan.ui.main.adapter.ArticleAdapter;
import com.wss.module.wan.ui.main.adapter.HomeMenuAdapter;
import com.wss.module.wan.ui.main.mvp.HomePresenter;
import com.wss.module.wan.ui.main.mvp.contract.HomeContract;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import ohos.aafwk.ability.Ability;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseMvpFragment<HomePresenter> implements HomeContract.View{

    Banner banner;

    AsymmetricRecyclerView rvMenuList;

    ListContainer rvArticleList;

    BgarefreshLayout refreshLayout;

    Component goTop;

    NestedScrollView scrollView;

    private ArticleAdapter articleAdapter;
    private List<Article> articleList = new ArrayList<>();
    private int page = 0;

    private HomeMenuAdapter homeMenuAdapter;
    private Ability ability;

    public HomeFragment(Ability ability) {
        super(ability);
        this.ability = ability;
    }

    @Override
    public void onViewCreated(Component view) {
        super.onViewCreated(view);
        init();
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    protected int getLayoutId() {
        return ResourceTable.Layout_wan_fragment_main;
    }

    @Override
    protected void initView() {
        findView();
        initRefresh();
        articleAdapter = new ArticleAdapter(context, articleList, new OnListItemClickListener<Article>() {
            @Override
            public void onItemClick(Article data, int position) {
                AbilityToAbility.toWebView(context, data.getLink());
            }
        });
        articleAdapter.setOnTagListener(new ArticleAdapter.OnTagClickListener() {
            @Override
            public void onCollectionClick(int position) {

            }
        });

        rvArticleList.setItemProvider(articleAdapter);

//        scrollView.setScrolledListener(new Component.ScrolledListener() {
//            @Override
//            public void onContentScrolled(Component component,
//                                          int scrollX,
//                                          int scrollY,
//                                          int oldScrollX,
//                                          int oldScrollY) {
//                if (scrollY >= PxUtils.getScreenHeight(context) / 5) {
//                    goTop.setVisibility(Component.VISIBLE);
//                } else if (scrollY < PxUtils.getScreenHeight(context) / 5) {
//                    goTop.setVisibility(Component.HIDE);
//                }
//            }
//        });

        rvMenuList.setRequestedColumnCount(4);
        homeMenuAdapter = new HomeMenuAdapter(context, new ArrayList<>(), new OnListItemClickListener<Template>() {
            @Override
            public void onItemClick(Template data, int position) {
                AbilityToAbility.toAbility(ability, data);
            }
        });
        rvMenuList.setItemProvider(new AsymmetricRecyclerViewAdapter<>(getContext(), rvMenuList, homeMenuAdapter));

        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                getPresenter().start();
            }
        }, 50);

    }

    private void findView() {
        banner = (Banner) getRootView().findComponentById(ResourceTable.Id_cb_banner);
        rvMenuList = (AsymmetricRecyclerView) getRootView().findComponentById(ResourceTable.Id_rv_block);
        rvArticleList = (ListContainer) getRootView().findComponentById(ResourceTable.Id_rv_list);
        refreshLayout = (BgarefreshLayout) getRootView().findComponentById(ResourceTable.Id_refresh_layout);
        goTop = getRootView().findComponentById(ResourceTable.Id_ll_go_top);

        goTop.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                scrollView.doFlingY(0);
//                scrollView.scrollTo(0, 0);
            }
        });
    }

    private void initRefresh() {
        BgaStickinessRefreshViewHolder stickinessRefreshViewHolder = new BgaStickinessRefreshViewHolder(context, true);
        refreshLayout.setRefreshViewHolder(stickinessRefreshViewHolder);
        refreshLayout.setIsShowLoadingMoreView(true);
        refreshLayout.setPullDownRefreshEnable(true);
        stickinessRefreshViewHolder.setPullDownRefreshText("释放立即刷新...");
        stickinessRefreshViewHolder.setLoadingMoreText("加载更多...");
        stickinessRefreshViewHolder.setUltimateColor(com.wss.common.base.ResourceTable.Color_gray);
        stickinessRefreshViewHolder.setLoadMoreBackgroundColorRes(com.wss.common.base.ResourceTable.Color_light_white);
        stickinessRefreshViewHolder.setRefreshViewBackgroundColorRes(com.wss.common.base.ResourceTable.Color_light_white);
        stickinessRefreshViewHolder.setLoaderTextColor(com.wss.common.base.ResourceTable.Color_gray);
        stickinessRefreshViewHolder.setPullUpDilogueVisible(false);
        stickinessRefreshViewHolder.setLoaderTextSize(40);
        stickinessRefreshViewHolder.setProgressSize(80);

        refreshLayout.setDelegate(new BgarefreshLayout.BgarefreshLayoutDelegate() {
            @Override
            public void onBgarefreshLayoutBeginRefreshing(BgarefreshLayout bgarefreshLayout) {
                resetPage();
            }

            @Override
            public boolean onBgarefreshLayoutBeginLoadingMore(BgarefreshLayout bgarefreshLayout) {
                getPresenter().getArticleList();
                return true;
            }
        });
    }

    private void resetPage() {
        page = 0;
        articleList.clear();
        articleAdapter.clear();
        getPresenter().getArticleList();
    }

    @Override
    public void refreshBannerList(List<BannerInfo> banners) {

        System.out.println("==== banners : " + banners.size());

        List<com.wss.common.bean.Banner> bannerList = new ArrayList<>();
        for (BannerInfo bannerInfo : banners) {
            bannerList.add(new com.wss.common.bean.Banner(bannerInfo.getImagePath(),
                    (bannerInfo.getUrl())));
        }

        ImageUtils.loadBanner(banner,
                bannerList,
                new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object o, Image image) {
                        if (o instanceof com.wss.common.bean.Banner) {
                            ImageUtils.loadImage(image, ((com.wss.common.bean.Banner) o).getImageUrl());
                        }
                    }
                },
                new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        AbilityToAbility.toWebView(context, bannerList.get(position).getRedirectUrl());
                    }
                });
    }

    @Override
    public void refreshMenuList(List<Template> menuList) {

        homeMenuAdapter.clear();
        homeMenuAdapter.addAll(menuList);
    }

    @Override
    public int getPage() {
        return page;
    }

    @Override
    public void refreshArticleList(List<Article> articles) {

        this.articleList.addAll(articles);
        articleAdapter.addAll(articles);
        articleAdapter.notifyDataChanged();
        page++;
        stopRefresh(refreshLayout);

    }

    @Override
    public void onActive() {
        super.onActive();
        banner.startAutoPlay();
    }

    @Override
    public void onInactive() {
        super.onInactive();
        banner.stopAutoPlay();
    }

    @Override
    public void onError(Object tag, String errorMsg) {
        stopRefresh(refreshLayout);
        if (getPage() > 0) {
            ToastUtils.show(errorMsg);
        } else {
            showErrorView(errorMsg);
        }
        super.onError(tag, errorMsg);
    }

    @Override
    public void onEmpty(Object tag) {
        super.onEmpty(tag);
        if (getPage() > 0) {
            ToastUtils.show("暂无更多数据啦~");
        } else {
            showEmptyView();
        }
        stopRefresh(refreshLayout);
    }

    @Override
    protected void onRefreshRetry() {
        super.onRefreshRetry();
        getPresenter().start();
    }
}
